package com.weasel.im.server.handler;

import com.weasel.im.common.domain.IMSession;
import com.weasel.im.common.domain.Message;
import com.weasel.im.common.manager.IMSessionManager;
import com.weasel.im.common.manager.LeaveMessageCacheManager;
import com.weasel.im.common.manager.UserSessionRelationManager;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**普通消息的处理类
 * Created by Dylan on 2015/12/3.
 */
public class CommonMessageHandler extends MessageHandler {

    private final static Logger logger = LoggerFactory.getLogger(CommonMessageHandler.class);

    public CommonMessageHandler( IMSessionManager sessionManager,UserSessionRelationManager relationManager, LeaveMessageCacheManager leaveMessageCacheManager) {
        super(sessionManager, relationManager, leaveMessageCacheManager);
    }

    public void handler(Channel channel, Message message) {

        String toUser = message.getTo();
        String sessionid = relationManager.getSessionidByUsername(toUser);
        IMSession session = sessionManager.get(sessionid);
        if(null != session){   //如果用户在线，就直接发送信息，否则就缓存起来留言
            logger.debug("[server] {} 对 {} 说:{}", new String[]{message.getFrom(), message.getTo(), message.getContent().toString()});
            Channel receiver = session.getChannel();
            receiver.writeAndFlush(message);
        }else{
            if(null == leaveMessageCacheManager){
                logger.debug("{} is not online,but system not leave message to he", toUser);
                return;
            }
            logger.debug("[server] {} 给 {} 留言说:{}", new String[]{message.getFrom(), message.getTo(), message.getContent().toString()});
            leaveMessageCacheManager.cache(message);
        }
    }

    public Message.Type handlerMessageType() {
        return Message.Type.COMMON;
    }
}
